<!--
 * @Description: 本地导入弹框 
 * @Author: 黄勇
 * @Date: 2020-03-09 15:36:26
 * @LastEditTime: 2020-09-28 10:15:55
 * @LastEditors: Please set LastEditors
 -->
<template>
  <el-dialog :title="localRefresh?'更新':'从本地导入'" :visible.sync="isShow" width="500px">
    <div>
      <el-input
        class="file-input"
        v-model="input"
        size="small"
        :placeholder="`请选择${fileType.join(',')}格式文件`"
        disabled
      >
      </el-input>
      <el-upload
        ref="upload"
        class="upload-file"
        :action="actionUrl"
        :data="upLoadData"
        name="importfile"
        :http-request="uploadFile"
        :on-success="onSuccess"
        :on-error="onError"
        :on-change="onChange"
        :on-progress="onProgress"
        :on-exceed="handleExceed"
        :show-file-list="false"
        :auto-upload="false"
        :file-list="fileList"
      >
        <el-button class="blueBtn" size="small" plain round type="primary">点击上传</el-button>
      </el-upload>
    </div>

    <!-- 检查应用是否存在提示框 -->
    <el-dialog
      title="提示"
      width="500px"
      :visible.sync="appCacheDialogShow"
      append-to-body
    >
      <app-icon
        slot="reference"
        iconName="vcloud-wodedingdan"
        className="org-info__icon cursor-pointer"
      ></app-icon>
      <span>当前应用已存在，是否生成为新应用</span>
      <br />

      <!-- 继续更新提示框 -->
      <!-- <el-dialog
        title="更新提示"
        :visible.sync="updateDialogShow"
        append-to-body
      >
        <app-icon
          slot="reference"
          iconName="vcloud-wodedingdan"
          className="org-info__icon cursor-pointer"
        ></app-icon>
        <span>
          系统将对应用"合同管理"进行更新，请务必做好该应用及数据库备份！
          应用更新后，无法还原到更新前版本！
        </span>
        <br />
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitUpdateBtn"
            >继续更新</el-button
          >
          <el-button @click="updateDialogShow = false">取 消</el-button>
        </span>
      </el-dialog> -->

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createAppBtn">确 认</el-button>
        <el-button @click="appCacheDialogShow = false">取 消</el-button>
      </span>
    </el-dialog>

    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitBtn">确 定</el-button>
      <el-button @click="closeDialog">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
// import loading from "@/utils/util.js"
import Axios from 'axios'

export default {
  name: 'upload',
  props: ['baseDataType'],
  components: {
    // loading
  },
  computed: {},
  data: () => ({
    appInfo:{},
    // 组件接口参数
    isShow: false,
    fileType: [],
    localRefresh: false,

    updateDialogShow: false, //继续更新提示弹框
    appCacheDialogShow: false, //应用已存在提示弹框
    upLoadData: {},
    input: '',
    fileList: [], //文件列表，目前只支持一个文件上传
    fileData: {},
    actionUrl: '#',
    targetCorpid: '',
  }),
  created() {},
  mounted() {},
  watch: {
    //input的值删除后，文件列表也需要删除
    input() {
      if (this.input == '') {
        this.fileList = []
        this.$refs.upload.clearFiles() //清除记录
      }
    },
  },
  methods: {
    // 组件入口
    open(data,appInfo={}) {
      this.appInfo = appInfo
      if (data) {
        this.input = ''
        if (this.$refs.upload) this.$refs.upload.clearFiles()
        // this.isShow = data.isShow;
        this.fileType = data.fileType
        this.localRefresh = data.localRefresh
        this.$nextTick(() => {
          this.isShow = true
          // this.getDesignCenterId();
        })
      }
    },
    //获取云设计中心id
    // getDesignCenterId(){
    //     this.api.getDesignCenterId(
    //         {},
    //         {method:"get",customRequest:true }
    //     ).then(res => {
    //         console.log(res);
    //         this.targetCorpid = res.data.corpid;
    //     }).catch(err => {
    //         console.log(err);
    //     });
    // },
    //文件状态发生改变时监听
    onChange(file) {
      if (file.status == 'ready') {
        // const fileType = file.name.split('.')[1] === 'wps';//格式
        const fileMaxSize = file.size / 1024 / 1024 < 100 //100M?
        //文件大小判断
        if (!fileMaxSize) {
          this.$message({
            message: `上传文件大小不能超过 100MB!`,
            type: 'warning'
          });
          return fileMaxSize
        }
        //判断传入的文件类型，与当前选择的文件的类型是否匹配
        let fileName = file.name.lastIndexOf('.')
        let fileNameLength = file.name.length //取到文件名长度
        let fileFormat = file.name.substring(fileName + 1, fileNameLength) //截
        if (this.fileType.indexOf(fileFormat) > -1) {
          this.fileList = []
          this.input = file.name
          this.fileList.push(file)
        } else {
          this.$message({
            message: `不支持此文件!`,
            type: 'warning'
          });
          return false
        }
        this.$refs.upload.clearFiles() //清除记录
      }
    },

    //文件上传成功时的钩子
    onSuccess(response, file, fileList) {
      this.$message({
        message: '文件上传成功',
        type: 'success',
      })
      this.$refs.upload.clearFiles() //清除记录
      // let data = {
      //     file:file
      // }
      // this.$emit("uploadSuccess", data)
    },

    //文件上传失败时的钩子
    onError(err, file, fileList) {
      this.$message.error(err.msg)
    },

    //文件上传时
    onProgress(event, file, fileList) {
      // this.$loading.show("上传中...");
      if (event.percent == 100) {
        //上传进度到100的时候
        // this.$loading.hide();
        // this.isShow = false;
      }
    },

    //文件选择个数监听
    handleExceed(files, fileList) {
      this.$message.warning('当前只允许选择1个文件!')
    },
    closeDialog() {
      this.fileList = []
      this.input = ''
      this.$refs.upload.clearFiles() //清除记录
      this.isShow = false
    },
    // 点击确定按钮
    submitBtn(file) {
      // this.isShow = false;
      if (this.fileList.length == 0) {
        this.$message.warning('请选择1个文件!')
        return
      }
      this.$refs.upload.submit()
    },
    //确定按钮后的文件上传
    uploadFile(params) {
      let config = {
        headers: { 'Content-Type': 'multipart/form-data' },
      }
      //从云设计中心 上传到目标客户
      const param = new FormData()
      param.append('file', params.file)

      const loading = this.$loading({
        lock: true,
        text:'上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      Axios.post(
        '/designgateway/designCenter',
        param,
        config,
        { timeout: 30000 } //最大上传时间
      )
      .then(res=>{
        const data = {fileId:res.data.data.id,createType:this.baseDataType==2?6:2}
        if(this.baseDataType==2){
          data.appId = this.$route.query.appId
        }
        const headers = {'Content-Type': 'application/json','AppEnv': this.baseDataType}
        return this.api.pkgUpload( data, { headers } )
      })
      .then((res) => {
        loading.close()
        let uploadData = res.data
        this.fileData.fileId = uploadData.fileId
          //执行安装之前，需要检查下应用是否已存在
        this.checkApp(uploadData)
      })
      .catch((err) => {
        loading.close()
      })
    },
    //检查应用是否已存在
    checkApp(uploadData) {
      const headers = {'Content-Type': 'application/json','AppEnv': this.baseDataType}
      this.api.checkAppInstall(
        {
          fileId: uploadData.fileId,
          createType:this.baseDataType==2?6:2
        },
        { headers } 
      )
      .then((res) => {
        let data = res.data
        if (this.localRefresh) {
          //是否是本地更新入口
          this.submitUpdateBtn() //直接更新
        } else {
          if (data.exist) {
            //如果重复
            this.appCacheDialogShow = true //打开更新提示,走本地更新
          } else {
            //如果不重复-直接走创建新应用
            const type = 1
            this.openAppInstall(type)
          }
        }
      })
    },
    //点击更新按钮
    updateBtn() {
      this.closeDialog()
      this.updateDialogShow = true
      this.appCacheDialogShow = false
    },
    //点击继续更新按钮
    submitUpdateBtn() {
      this.closeDialog()
      this.updateDialogShow = false
      const type = 2
      this.openAppInstall(type)
    },
    //点击生成新应用按钮
    createAppBtn() {
      this.closeDialog()
      this.appCacheDialogShow = false
      const type = 1
      this.openAppInstall(type)
    },
    //触发最终回调
    openAppInstall(type) {
      //type 1  创建新应用   2 本地更新应用   3 更新在线应用
      const fileId = this.fileData.fileId
      const params = {
        fileId: fileId,
        type: type,
      }
      var data = {
        url: '',
        title: '应用安装向导',
        source: '',
        fileId: fileId,
        setupType: 'local',
        resetId: false,
        upgrade: type == 1 ? false : true, //true:更新 false:生成新应用
        upgradeAppId: type == 2 ? this.appInfo.id : '',
        version: '',
      }
      params.data = data
      this.closeDialog()
      if(this.baseDataType==2){
        this.$emit('openAppInstall', params, {source:6})
      }else{
        const sourceData = type==2 ? {source:7} : {source:2}
        this.$emit('openAppInstall', params, sourceData)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.file-input {
  width: 310px;
  margin-right: 20px;
  /deep/ input {
    color: #666 !important;
    &:disabled::placeholder {
      color: #666 !important;
    }

    &:disabled::-webkit-input-placeholder {
        /* WebKit browsers 适配谷歌 */
        color: #666 !important;
    }

    &:disabled:-moz-placeholder {
        /* Mozilla Firefox 4 to 18 适配火狐 */
        color: #666 !important;
    }

    &:disabled::-moz-placeholder {
        /* Mozilla Firefox 19+ 适配火狐 */
        color: #666 !important;
    }

    &:disabled:-ms-input-placeholder {
        /* Internet Explorer 10+  适配ie*/
        color: #666 !important;
    }
  }
}
.upload-file {
  display: inline-block;
  button {
    width: 120px;
  }
}
</style>
